package org.example;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 动态服务器上下线
 */
public class DynamicServerUpAndDownServer {

    private String connectString = "10.211.55.102:2181,10.211.55.103:2181,10.211.55.104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DynamicServerUpAndDownServer ds = new DynamicServerUpAndDownServer();
        // 获取 zk连接
        ds.zkClient = new ZooKeeper(ds.connectString, ds.sessionTimeout, event -> {

        });

        // 主鹅册服务器到zk集群
        ds.register(args[0]);

        //启动业务逻辑
        ds.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    public void register(String hostname) throws InterruptedException, KeeperException {
        //  ---servers
        //        server0000000001 server0000000002
        String s = zkClient.create("/servers/server", hostname.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + "已经上线");
    }
}

